package com.quandou.base.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof String && principal.equals("anonymousUser"))
            throw new AccessDeniedException("没有权限");
        if (principal instanceof User) {
            User user = (User) principal;
            if (user.getUsername().equals("admin")) {
                return;
            }
        }
        List<String> authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        configAttributes.forEach(ca -> {
            String needRole = ca.getAttribute();
            if (needRole.equals("ROLE_LOGIN"))
                return;
            if (!authorities.contains(needRole))
                throw new AccessDeniedException("没有权限");
        });
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
